import React, { useState, useEffect } from 'react'
import { Breadcrumb, Card, Table, Button, Col, Row, Input, Switch, Modal, Form, Popconfirm, message } from 'antd'
import Select from '../../../component/Select'
import { delectSeleOffice, getCity, getArea, getOffice, deleteOffice, updateOffice, addOffice, searchValueOffice, selectValOffice, changeSwitchOffice } from '../../../api/index'

const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
};
const Sell = () => {
    const [officeList, setOfficeList] = useState([])
    const [city, setCity] = useState([])
    const [area, setArea] = useState([])
    const [state, setState] = useState(['请选择', '开启', '禁用'])
    const [selectionType, setSelectionType] = useState('checkbox');
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isEdit, setIsEdit] = useState(false)
    const [form] = Form.useForm();
    const [record, setRecord] = useState({})
    const [seaValue, setSeaValue] = useState('')
    const [selection, setSelection] = useState([])
    useEffect(() => {
        getCityList()
        getAreaList()
        getOfficeList()
    }, [])
    const columns = [
        {
            title: '楼盘名称',
            dataIndex: 'name',
        },
        {
            title: '标题',
            dataIndex: 'house',
        },
        {
            title: '面积',
            dataIndex: 'acreage',
            defaultSortOrder: 'descend',
            sorter: (a, b) => a.acreage-b.acreage,
        },
        {
            title: '总价',
            dataIndex: 'price'
        },
        {
            title: '排名',
            dataIndex: 'range',
        },
        {
            title: '状态',
            dataIndex: 'state',
            render: (state, record) => {
                return <Switch checked={state === '开启' ? true : false} onChange={(e) => onChangeSwitch(e, record)} />
            }
        }, {
            title: '操作',
            dataIndex: 'action',
            render: (text, record) => {
                return <div>
                    <Button type='text' onClick={() => edit(record)}>编辑</Button>
                    <Popconfirm
                        title="确定删除吗"
                        onConfirm={() => confirm(record)}
                        onCancel={cancel}
                        okText="Yes"
                        cancelText="No"
                    >
                        <Button type='text'>删除</Button>
                    </Popconfirm>
                </div>
            }
        }
    ];
    //复选框
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            setSelection([...selectedRowKeys])
        },
    };
    //批量删除
    const confirmSelect = async () => {
        const { data: res } = await delectSeleOffice({ selection })
        if (res.code === 0) {
            message.success(res.msg)
            console.log(res.data)
            setOfficeList([...res.data])
        }
    }
    //获取城市列表
    const getCityList = async () => {
        const { data: res } = await getCity()
        let city = res.body.map(item => item.label)
        city.unshift('请选择')
        setCity([...city])
    }
    //获取区列表
    const getAreaList = async () => {
        const { data: res } = await getArea()
        let area = res.body.map(item => item.label)
        area.unshift('请选择')
        setArea([...area])
    }
    //获取小区列表
    const getOfficeList = async () => {
        const { data: res } = await getOffice()
        if (res.code === 0) {
            message.success(res.msg)
            setOfficeList([...res.data])
        }
    }
    //开关
    const onChangeSwitch = async (checked, record) => {
        const { data: res } = await changeSwitchOffice({ state: checked, record })
        if (res.code === 0) {
            message.success(res.msg)
            setOfficeList([...res.data])
        }
    }
    //编辑
    const edit = async (record) => {
        form.setFieldsValue(record)
        setIsModalVisible(true)
        setIsEdit(true)
        setRecord({ ...record })
    }
    //点击确认
    const handleOk = () => {
        if (isEdit) {
            editItem()
        } else {
            addItem()
        }
        setIsModalVisible(false);
    };
    //编辑
    const editItem = async () => {
        const formItem = { ...record, ...form.getFieldValue() }
        const { data: res } = await updateOffice({ ...formItem })
        if (res.code === 0) {
            message.success(res.msg)
            setOfficeList([...res.data])
        }
    }
    //添加
    const addItem = async () => {
        const formItem = form.getFieldValue()
        formItem.key = Math.random().toString().slice(2, 8)
        formItem.range = officeList.length + 1
        formItem.state = '开启'
        const { data: res } = await addOffice({ ...formItem })
        if (res.code === 0) {
            message.success(res.msg)
            setOfficeList([...res.data])
        }
    }
    //点击取消
    const handleCancel = () => {
        setIsModalVisible(false);
    };
    //确认删除
    const confirm = (record) => {
        deleteItem(record)
        message.success('删除成功');
    }
    //取消删除
    const cancel = (e) => {
        message.error('取消成功');
    }
    //删除
    const deleteItem = async (record) => {
        const { data: res } = await deleteOffice({ id: record.key })
        setOfficeList([...res.data])
    }
    //模糊搜索
    const onChange = (e) => {
        setSeaValue(e.target.value)
    }
    //回车按下
    const pressEnter = async () => {
        if (seaValue === '') {
            getOfficeList()
        } else {
            const { data: res } = await searchValueOffice(seaValue)
            if (res.code === 0) {
                message.success(res.msg)
                setOfficeList([...res.data])
            } else {
                message.error(res.msg)
            }
        }
    }
    //选择器
    const selectValue = async (value) => {
        console.log(value)
        if (value === '请选择') {
            getOfficeList()
        } else {
            const { data: res } = await selectValOffice({ value })
            if (res.code === 0) {
                message.success(res.msg)
                setOfficeList([...res.data])
            } else {
                message.error(res.msg)
            }
        }
    }
    return <div className="community">
        <Card>
            <Breadcrumb>
                <Breadcrumb.Item>
                    <a href="/home">首页</a>
                </Breadcrumb.Item>
                <Breadcrumb.Item>
                    <a href="/home/sellOffice">商业</a>
                </Breadcrumb.Item>
                <Breadcrumb.Item>
                    <a href="/home/sellOffice">写字楼</a>
                </Breadcrumb.Item>
                <Breadcrumb.Item>
                    <a href="/home/sellOffice">出售管理</a>
                </Breadcrumb.Item>
            </Breadcrumb>
        </Card>
        <Row gutter={16}>
            <Col className="gutter-row" span={4}>
                <Select type={city} selectValue={selectValue}></Select>
            </Col>
            <Col className="gutter-row" span={4}>
                <Select type={area} selectValue={selectValue}></Select>
            </Col>
            <Col className="gutter-row" span={4}>
                <Input placeholder="搜索小区名称" allowClear={true} value={seaValue} onChange={onChange} onPressEnter={pressEnter} style={{ width: '100%', margin: '10px 0' }} />
            </Col>
            <Col className="gutter-row" span={4}>
                <Select type={state} selectValue={selectValue}></Select>
            </Col>
            <Col className="gutter-row" span={4}>
                <Button type='primary' style={{ width: '100%', margin: '10px 0' }} onClick={() => { setSeaValue(''); getOfficeList(); }}>重置</Button>
            </Col>
            <Col className="gutter-row" span={4}>
                <Button type='primary' style={{ width: '100%', margin: '10px 0' }} onClick={() => {
                    form.setFieldsValue({ name: '', house: '', price: '', acreage: '' });
                    setIsModalVisible(true);
                    setIsEdit(false);
                }}>新建</Button>
            </Col>
            <Col className="gutter-row" span={4}>
                <Popconfirm
                    title="确定删除吗"
                    onConfirm={confirmSelect}
                    onCancel={cancel}
                    okText="Yes"
                    cancelText="No"
                >
                    <Button type='primary' style={{ width: '100%', margin: '10px 0' }}>删除</Button>
                </Popconfirm>
            </Col>
        </Row>
        <Card style={{ width: '100%', height: '100%' }}>
            <Table
                rowSelection={{
                    type: selectionType,
                    ...rowSelection,
                }}
                columns={columns}
                dataSource={officeList}
                pagination={{
                    defaultPageSize: 5,
                    defaultCurrent: 1
                }}
            />
        </Card>
        <Modal title={isEdit ? "编辑内容" : "添加信息"} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
            <Form
                {...layout}
                form={form}
                name="basic"
                initialValues={{ remember: true }}
            >
                <Form.Item
                    label="楼盘名称"
                    name="name"
                    rules={[{ required: true, message: '请输入楼盘名称' }]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="标题"
                    name="house"
                    rules={[{ required: true, message: '请输入房型' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="价格"
                    name="price"
                    rules={[{ required: true, message: '请输入价格' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="占地面积"
                    name="acreage"
                    rules={[{ required: true, message: '请输入面积' }]}
                >
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    </div>
}

export default Sell